<template>
	<view class="content">
	  <view class="index-header">
		<view class="logo">
			<!-- <image src='../../static/home_logo.jpg' mode="widthFix"> </image> -->
			<image :src="$getImageSrc('home_logo.png')" mode="widthFix"> </image> 
		</view>
		<view class="positon" @click="goChooseAddress">
			<image class="dw" :src='$getImageSrc("home_ic_dw.png")'> </image> 
			<text class="ellipsis name">{{address}}</text>
			<image class="more" :src='$getImageSrc("home_ic_dsj.png")'> </image> 
		</view>	  
	  </view>
	  <view class="banner-info">
				<swiper class="swiper-box" 
				 :autoplay='true' 
				interval='5000' :indicator-dots='true'
				indicator-active-color='#02B1AA'
				>
					<swiper-item v-for="(item, index) in bannerlist" :key="index" @click="goInfo(index)">
						<view class="swiper-item" :class="'swiper-item' + index">
							<image class="banner" :src="item.imgUrl"></image>
						</view>
					</swiper-item>
				</swiper>
		  <view class="tip-info"  @click="goOrderList" v-if='awaitOrder'>
			 <text class="tipInfo">您有订单正在服务中...</text> 
			 <view class="goDeatil flexBC">
				 <text>立即查看</text>
				 <image class="banner" :src='$getImageSrc("home_ic_more.png")'></image>
			 </view>
		  </view>
		  <view class="mainTitle">
			  洗车方案
		  </view>
		  <view class="planlist" v-if='planItems.length > 0'>
		      <view v-for="(item, i) in planItems" :key="i"  @click="goPlanDetail(item)">
		      	 <plan-item :planInfo='item'></plan-item>
		      </view>
			  <view style="height:120rpx" v-if='showWashBtn'></view>
		  </view>
		  <no-list tipInfo="附近暂无可选方案" v-else></no-list>
	  </view>
	   
      <view class="order-btn"  v-if='showWashBtn' @click="goWashCart">一键预约</view>
	 <uni-popup ref="loginPopup" :mask-click="false">
		 <view class="popup-content" v-if='popup==="login"'>
		 	<view class="popup-title">授权登录</view>
			<view class="popup-tip-info">
				为了更好的为您服务，请先登录
			</view>
			<view class="popup-btns">
				<!-- #ifdef MP-ALIPAY -->
				<button class="btn" open-type="getAuthorize" scope='userInfo' type="primary" @getAuthorize="onGetAuthorize">支付宝一键授权</button>
				<!-- #endif -->
				<!-- #ifdef MP-WEIXIN -->
				<button class="btn" open-type="getUserInfo" type="primary"  @getuserinfo="getUserInfo">微信一键授权</button>
				<!-- #endif -->
				<button class="btn btn1" type="default" @click="close">暂不登录</button>
				<view class="popup-info" @click="agree = !agree">
					<image style="width: 26rpx;height: 26rpx;" :src="$getImageSrc(agree?'ic_xz_select.png':'ic_xz.png')" mode=""></image>
					<text>我已阅读并同意以下协议</text>
					<text class="xys" @click.stop="goYSXY">《隐私协议》</text></view>
			</view>
		 </view>
		 <view class="dw-popup" v-if='popup==="dw"'>
		 	<image class="dw-icon" :src="$getImageSrc('pop_img_dw.png')" mode=""></image>
			<view class="dw-title">
				开启定位
			</view>
			<view class="dw-info">
				开启定位权限获取附近洗车方案吧
			</view>
			<button class="regist" @click="close" type="primary">去认证</button>
		 </view>
	 </uni-popup>
	</view>
</template>

<script>
	import {wxlogin, showable, nearStore, regeo, memberIndex, myInfo, myCart} from "@/untils/api"
	import configs from '@/untils/configs'
	export default {
		data() {
			return {
				userInfo: null,
				hasUserInfo: false,
				planItems: [],
				bannerlist:[],
				awaitOrder:'',
				showWashBtn:false,
				agree:false,
				popup:'login',
				address:'',
				info: [{
					content: '内容 A'
				}, {
					content: '内容 B'
				}, {
					content: '内容 C'
				}],
				current: 0,
			}
		},
		components:{
		},
		// async onLoad(option) {
		// 	if(option.islogin){
		// 		this.open()
		// 	}else{
		// 		let location = this.$getStorageSync('location')
		// 		if(location){
		// 			let address = this.$getStorageSync('address')
		// 			this.address = address.township
		// 			this.getNearstore()
		// 		}else{
		// 			await this.getlocation()
		// 		}
			   
		// 	}
		// },
		  async mounted(){
			//   console.log('------123', this.$mp)
			 if(this.$mp.query.islogin){
			 	this.open()
			 }else{
				 await this.getlocation()
			 	// let location = this.$getStorageSync('location')
			 	// if(location){
			 	// 	let address = this.$getStorageSync('address')
			 	// 	this.address = address.township
			 	// 	this.getNearstore()
			 	// }else{
			 	// 	await this.getlocation()
			 	// }
			    
			 }
			 this.$removeStorageSync('seriveParams')
			 this.$removeStorageSync('selectPlanInfo')
			 this.$removeStorageSync('selectCartInfo')
		  },
		
		methods: {
			goYSXY(){
			 uni.navigateTo({
			 	url:'/subpackage/mine/ystk'
			 })
			},
			goInfo(index){
				this.$setStorageSync('bannerInfo', this.bannerlist[index])
				uni.navigateTo({
					url:'/subpackage/mine/bannerInfo'
				})
			},
			onGetAuthorize(e){
				console.log('-----onGetAuthorize', e)
				my.getAuthCode((res) => {
					console.log(res.authcode)
					this.$setStorageSync('satoken', 'bdba5837-8995-4639-9464-00aa9596a665')
					// this.$setStorageSync('userInfo', {nickname:res.data.nickname, avatar:res.data.avatar})
					uni.reLaunch({
						url:'/pages/index/index',
						success:()=>{
							this.close()
						}
					})
				})
			},
		  // 获取用户信息
		  getUserInfo(e) {
			if (e.mp.detail.userInfo) {
			  this.userInfo = e.mp.detail.userInfo;
			  this.hasUserInfo = true;
			  this.login();
			} else {
			  uni.showModal({
				title: '警告',
				content: '您点击了拒绝授权，将无法进入小程序，请授权之后再进入!',
				showCancel: false,
				confirmText: '返回授权',
				success: function(res) {
				  if (res.confirm) {
					console.log('用户点击了“返回授权”');
				  }
				}
			  });
			}
		  },
		  // 登录并获取用户信息
		  login() {
			uni.login({
			  provider: 'weixin',
			  success: (loginRes) => {
				// 登录成功，获取用户code
				const { code } = loginRes;
				uni.getUserInfo({
					 desc: '获取您的位置，头像，昵称；用于完善用户资料信息', 
					success:(userInfo) => {
						const {rawData, signature, encryptedData, iv} = userInfo
						let params = {
							appid: configs.APPID,
							code,rawData, signature, encryptedData, iv
						}
						wxlogin(params).then((res) => {
							if(res.code - 200 !== 0){
								console.error('登录信息错误',res.msg)
								return false;
							}
							this.$setStorageSync('satoken',res.data.tokenValue)
							this.$setStorageSync('userInfo', {nickname:res.data.nickname, avatar:res.data.avatar})
							uni.reLaunch({
								url:'/pages/index/index',
								success:()=>{
									this.close()
								}
							})
						})
					}
				})
				// 发送code到后台换取openId, sessionKey, unionId
			  },
			  fail: (err) => {
				console.log('uni.login 接口调用失败，将无法正常使用开放接口等服务', err);
				uni.showToast({
				  title: '登录失败',
				  icon: 'none'
				});
			  }
			});
		  },
		  getlocation(){
			  return new Promise((resolve, reject) => {
				  uni.getLocation({
					type: 'gcj02',
					success:  (res) => {
						// console.log('当前经纬度信息：' , res);
						// res = {longitude:'104.73830599999997', latitude:'31.460719999999974'}
						// this.longitude = res.longitude
						// this.latitude = res.latitude
						this.$setStorageSync('location', {longitude:res.longitude,latitude:res.latitude})
						regeo({lat:res.latitude, lng: res.longitude}).then((res) => {
							this.$setStorageSync('address', res.data)
							this.address = res.data.township
							this.getNearstore()
							resolve(res.data)
						}).catch((err) => {
							uni.showToast({
								title:JSON.stringify(err)
							})
						})
					},
					fail:()=>{
						this.address = '未获取到定位信息'
						this.getIndex()
					}
				})
			  })
		  },

		  // 定位授权
		  reAuthorize() {
			let that = this;
		    uni.showModal({
		      title: '提示',
		      content: '需要您同意获取定位权限',
		      success: function (res) {
		        if (res.confirm) {
		          // 打开设置页面
		          uni.openSetting({
		            success: function (settingData) {
		              if (settingData.authSetting['scope.userLocation']) {
		                // 用户已经同意授权
						uni.showToast({
							icon:'none',
							title: '授权成功',
							duration: 2000
						});
						that.getlocation()
		              } else {
		                // 用户拒绝授权
		                console.log('用户拒绝授权');
						uni.showToast({
							icon:'none',
							title: '您已拒绝了授权,无法获取定位',
							duration: 3000
						}); 
		              }
		            }
		          });
		        }
		      }
		    });
		  },
		  goChooseAddress(){
			  let location = this.$getStorageSync('location') || ''
			//   this.reAuthorize()
			  if(!location){
				  this.reAuthorize()
				  return false;
				  uni.getSetting({
				  	success:(res) => {
						if(res.authSetting['scope.userLocation']){
							// 打开地图， 选择位置
							uni.chooseLocation({
								success: res => {
									console.log(res);
									console.log('位置名称：' + res.name);
									console.log('详细地址：' + res.address);
									console.log('纬度：' + res.latitude);
									console.log('经度：' + res.longitude);
								}
							}); 
						}else{
						   this.reAuthorize()
						}
					}
				  })
				  return false;
			  }
			  
		  },
		  getPlanItems(){
			showable().then((res) => {
				console.log('----showable', res)
			})  
		  },
		  
		  goPlanDetail(item){
			  uni.navigateTo({
			  	url:'/pages/index/projectInfo?id='+item.id
			  })
		  },
		  getIndex(){
            memberIndex().then((res) => {
				if(res.code - 200 === 0){
					const {service, washMenu, banners} = res.data
					this.planItems = washMenu
					this.awaitOrder = service
					this.bannerlist = banners
				}else{
					
				}
			})
		  },
		  getDefaultCart(){
			myInfo().then((res) => {
				this.$setStorageSync('defaultCart', res.data)
			})  
		  },
		  getCarts(){
			  myCart().then((res) => {
				this.$setStorageSync('cartlist', res.data)
			  })
		  },
		  async getNearstore(){
			  this.getIndex()
			  let location = this.$getStorageSync('location') || ''
			 //  if(!location){
				// await this.getlocation()
				// this.getNearstore()
				// return false;
			 //  }
			  let params = {lat: location.latitude,lng: location.longitude}
			  nearStore(params).then((res) => {
				  if(res.data.content.length>0){
                    this.$setStorageSync('nearStore', 1)
					this.showWashBtn = true
				  }else{
					this.$setStorageSync('nearStore', '')
					this.showWashBtn = false
				  }
			  })
			  this.getDefaultCart()
			  this.getCarts()
		  },
		  goWashCart(){
			uni.navigateTo({
				url:'/subpackage/orderWashCar/index'
			})  
		  },
		  goOrderList(){
             uni.switchTab({
				url: '/pages/order/index'
			 });
		  },
          open(){
			 uni.hideTabBar();
			 this.$refs.loginPopup.open()
		  },
		  close(){
			 uni.showTabBar();
			 this.$refs.loginPopup.close()
		  }
		}
	}
</script>

<style  lang="scss" scoped>
	.content {
		height: 100%;
		display: flex;
		flex-direction: column;
		background-image: url('https://static.myxiangyu.com/image/bg/bg_home.png');
		background-repeat:no-repeat;
		background-position: top;
		background-size: 100%;
		overflow: auto;
		position: relative;
		/* margin-top: -48px; */
		.index-header{
			width: 96%;
			margin: 0 auto;
			height: 200rpx;
			display: flex;
			justify-content: space-between;
			align-items: flex-end;
			// overflow: hidden;
			// position: absolute;
			// top: 100rpx;
			margin-top: 100rpx;
			margin-bottom: 20rpx;
			z-index: 99;
		}
			.logo{
				image{
					width: 100rpx;
					// height: 124rpx;
					margin-left: 28rpx;
				}
			}
			.positon{
				display: flex;
				font-size: 28rpx;
				line-height: 32rpx;
				margin-bottom: 20rpx;
				.dw{
					width: 32rpx;
					height: 32rpx;
					margin-right: 10rpx;
				}
				.name{
					max-width: 300rpx;
				}
				.more{
					width: 28rpx;
					height: 16rpx;
					margin-top: 10rpx;
					margin-left: 10rpx;
				}
		}
		.banner-info{
			width: 686rpx;
			margin: 0 auto;
			.swiper-box{
				height: 240rpx;
			}
			.banner{
				border-radius: 20rpx;
				width: 100%;
				height: 240rpx;
			}
			.tip-info{
				width: 100%;
				height: 80rpx;
				background-color: rgba(255, 96, 36, .1);
				color: #FF6024;
				font-size: 24rpx;
				display: flex;
				justify-content: space-between;
				align-items: center;
				border-radius: 20rpx;
				margin-top: 14rpx;
				.tipInfo{
					margin-left: 20rpx;
				}
				.goDeatil{
					display: flex;
					margin-right: 20rpx;
					image{
						width: 20rpx;
						height: 20rpx;
						margin-left: 10rpx;
					}
				}
			}
			.planlist{
				width: 100%;
				margin-top: 20rpx;
				overflow: hidden;
			}
			
		}
		.order-btn{
			position: fixed;
			bottom: 40rpx;
			line-height: 88rpx;
			width: 686rpx;
			height: 88rpx;
			background: linear-gradient( 225deg, #8AF3B3 0%, #02B1AA 100%);
			box-shadow: 0px 0px 12px 1px rgba(2,177,170,0.3);
			border-radius: 8px 8px 8px 8px;
			color: #fff;
			text-align: center;
			left: 32rpx;
		}
		.popup-content{
			width: 550rpx;
			height: 450rpx;
			padding: 40rpx;
			background:#fff;
			border-radius: 10rpx;
			font-size: 24rpx;
			text-align: center;
			padding-top: 80rpx;
			background: #fff linear-gradient( 180deg, rgba(2,177,170,0.12) 0%, rgba(0,214,142,0) 20%);
			border-radius: 16rpx 16rpx 16rpx 16rpx;
			.popup-title{
				font-size: 32rpx;
				font-weight: 600;
				line-height: 40rpx;
			}
			.popup-tip-info{
				line-height: 80rpx;
			}
			.popup-btns{
				width: 400rpx;
				margin: 0 auto;
				.btn{
					height: 80rpx;
					line-height: 80rpx;
					font-size: 26rpx;
					margin-bottom: 30rpx;
				}
				.btn1{
					background: #eee;
				}
				.popup-info{
					font-size: 24rpx;
					line-height: 26rpx;
				    image{
					   margin-right: 10rpx;
				   }
				   .xys{
					   color: #02B1AA;
				   }
				}
			}
		}
		.dw-popup{
		  width: 550rpx;
		  height: 450rpx;
		  background: #fff linear-gradient( 180deg, rgba(2,177,170,0.12) 0%, rgba(0,214,142,0) 20%);
		  border-radius: 16rpx 16rpx 16rpx 16rpx;
		  border-radius: 20rpx;
		  position: relative;
		  text-align: center;
		  .dw-icon{
			  width: 180rpx;
			  height: 180rpx;
			  position: absolute;
			  top: -100rpx;
              left: 180rpx;			  
		  }
		  .dw-title{
			  padding-top:70rpx ;
			  line-height: 70rpx;
			  font-size: 36rpx;
			  font-weight: 800;
		  }
		 .dw-info{
			 font-size: 24rpx;
			 line-height: 60rpx;
		 }
		 .regist{
			 width: 400rpx;
			 height: 80rpx;
			 line-height: 80rpx;
			 font-size: 30rpx;
			 position: absolute;
			 bottom: 40rpx;
			 left: 80rpx;
			 background-color: #02B1AA;
		 }
		}
	}
</style>
